package com.zte.rest;


import com.atlassian.confluence.core.ContentEntityObject;
import com.atlassian.confluence.internal.ContentEntityManagerInternal;
import com.atlassian.confluence.pages.Comment;
import com.atlassian.confluence.security.SpacePermission;
import com.atlassian.confluence.security.SpacePermissionManager;
import com.atlassian.confluence.spaces.Space;
import com.atlassian.confluence.spaces.SpaceManager;
import com.atlassian.confluence.user.UserAccessor;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.atlassian.user.EntityException;
import com.atlassian.user.GroupManager;
import com.atlassian.user.User;
import com.atlassian.user.UserManager;
import com.atlassian.user.search.page.Pager;

import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.*;


@Path("/space")
@Named("spaceService")
public class SpaceService {

    @ComponentImport
    protected UserAccessor userAccessor;

    @ComponentImport
    protected SpaceManager spaceManager;

    @ComponentImport
    protected SpacePermissionManager spacePermissionManager;

    @ComponentImport
    protected GroupManager groupManager;

    @ComponentImport
    protected UserManager userManager;

    @ComponentImport
    protected ContentEntityManagerInternal contentEntityManagerInternal;

    @Inject
    public SpaceService(UserAccessor userAccessor, SpaceManager spaceManager, SpacePermissionManager spacePermissionManager,
                        GroupManager groupManager, UserManager userManager, ContentEntityManagerInternal contentEntityManagerInternal) {
        this.userAccessor = userAccessor;
        this.spaceManager = spaceManager;
        this.spacePermissionManager = spacePermissionManager;
        this.groupManager = groupManager;
        this.userManager = userManager;
        this.contentEntityManagerInternal = contentEntityManagerInternal;
    }

    @Path("getAllSpaces")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response getAllSpaces() {
        List<Space> spaces = spaceManager.getAllSpaces();
        List<Map> spaceModelList = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (Space space : spaces) {
            Map spaceModel = new HashMap();
            spaceModel.put("spaceName", space.getName());
            spaceModel.put("spaceKey", space.getKey());
            spaceModel.put("spaceType", space.getSpaceType().toI18NKey());
            if (space.getHomePage() != null) {
                spaceModel.put("homePage", space.getHomePage().getUrlPath());
            }
            if (space.getCreator() != null) {
                spaceModel.put("creator", space.getCreator().getFullName());
            }
            spaceModel.put("createDate", space.getCreationDate().toString());
            spaceModelList.add(spaceModel);
        }
        return Response.ok(spaceModelList).build();
    }

    @Path("getSpaceAdministor")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response getSpaceAdministor(@QueryParam("spaceKey") String spaceKey) {
        Space space = spaceManager.getSpace(spaceKey);
        StringBuilder sb = new StringBuilder();
        List<SpacePermission> permissionList = space.getPermissions();
        for (SpacePermission spacePermission : permissionList) {
            if (spacePermission.isUserPermission() && spacePermission.getType().equalsIgnoreCase(SpacePermission.ADMINISTER_SPACE_PERMISSION.toString())) {
                String fullName = spacePermission.getUserSubject().getFullName();
                sb.append(fullName).append(" ");
            }
        }
        return Response.ok(sb.toString()).build();
    }

    @Path("getSpaceGroups")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response getSpaceGroups(@QueryParam("spaceKey") String spaceKey) {
        Space space = spaceManager.getSpace(spaceKey);
        StringBuilder sb = new StringBuilder();
        List<SpacePermission> permissionList = space.getPermissions();
        Set<String> groups = new HashSet<>();
        for (SpacePermission spacePermission : permissionList) {
            if (spacePermission.isGroupPermission()) {
                String group = spacePermission.getGroup();
                if ("confluence-users".equals(group) || "confluence-administrators".equals(group) || groups.contains(group))
                    continue;
                groups.add(group);
                sb.append("<").append(group).append(":");
                try {
                    Pager<String> members = groupManager.getMemberNames(groupManager.getGroup(group));
                    Iterator<String> iterator = members.iterator();
                    while (iterator.hasNext()) {
                        User user = userManager.getUser(iterator.next());
                        if (user != null) {
                            sb.append(user.getFullName()).append(" ");
                        }
                    }
                    sb.append("> ");
                } catch (EntityException e) {
                    e.printStackTrace();
                }
            }
        }
        return Response.ok(sb.toString()).build();
    }


    @Path("getComments")
    @GET
    @AnonymousAllowed
    @Produces({MediaType.APPLICATION_JSON})
    public Response getComments(@QueryParam("id") long id) {
        ContentEntityObject contentEntityObject = contentEntityManagerInternal.getById(id);
        List<Comment> comments = contentEntityObject.getComments();
        Map<String, String> commentMap = new HashMap<>();
        List<Object> list = new ArrayList<>();
        for (Comment comment : comments) {
            commentMap.put("creator", comment.getCreator().getFullName());
            commentMap.put("content", comment.getBodyAsStringWithoutMarkup());
            list.add(commentMap);
        }
        return Response.ok(list).build();
    }

    @Path("getSpacePermissions")
    @POST
    @Produces({MediaType.APPLICATION_JSON})
    public Response getSpacePermissions(@QueryParam("spaceKey") String spaceKey) {
        Space space = spaceManager.getSpace(spaceKey);
        StringBuilder sb = new StringBuilder();
        List<SpacePermission> permissionList = space.getPermissions();

        List<Map<String, String>> list = new ArrayList<>();
        for (SpacePermission spacePermission : permissionList) {
            Map<String, String> map = new HashMap<>();
            if (spacePermission.isUserPermission()) {
                map.put("name", spacePermission.getUserSubject().getFullName());
                map.put("type", spacePermission.getType());
            } else if (spacePermission.isGroupPermission()) {
                map.put("name", spacePermission.getGroup());
                map.put("type", spacePermission.getType());
            }
            list.add(map);
        }
        return Response.ok(list).build();
    }

}